package com.sikaryofficial.system.api.util;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import com.sikaryofficial.system.api.domain.SysUser;
import lombok.extern.slf4j.Slf4j;

import java.security.SecureRandom;

/**
 * @author : qinjinyuan
 * @desc : TODO  请填写你的功能描述
 * @date : 2024/05/20 16:31
 */
@Slf4j
public class NickNameGen {
    private static final String RANDOM_SUFFIX_CHAR_POOL = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final int NICKNAME_SUFFIX_LENGTH = 3;
    private static final int MAX_NICKNAME_LENGTH = 8;
    private static final SecureRandom secureRandom = new SecureRandom();

    public static String generateNicknameFromEmailPrefix(String emailPrefix) {
        String nicknamePrefix = "";
        if (CharSequenceUtil.isNotBlank(emailPrefix)) {
            emailPrefix = emailPrefix.indexOf("@") > 0 ? emailPrefix.substring(0, emailPrefix.indexOf("@")) : emailPrefix;
            // 从邮箱前缀中提取昵称的前半部分
            nicknamePrefix = emailPrefix.substring(0, Math.min(emailPrefix.length(), NICKNAME_SUFFIX_LENGTH));
        }
        // 生成随机后缀
        StringBuilder suffixBuilder = new StringBuilder(NICKNAME_SUFFIX_LENGTH);
        int appendLen = MAX_NICKNAME_LENGTH - nicknamePrefix.length();
        for (int i = 0; i < appendLen; i++) {
            suffixBuilder.append(RANDOM_SUFFIX_CHAR_POOL.charAt(secureRandom.nextInt(RANDOM_SUFFIX_CHAR_POOL.length())));
        }
        // 合成完整的昵称
        String nicknameSuffix = suffixBuilder.toString();
        return nicknamePrefix + nicknameSuffix;
    }

    public static void buildNickNameAndUserId(SysUser user) {
        if (CharSequenceUtil.isNotBlank(user.getEmail())) {
            try {
                user.setNickName(NickNameGen.generateNicknameFromEmailPrefix(user.getEmail()));
            } catch (Exception e) {
                log.error("NickNameGen.generateNicknameFromEmailPrefix error: " + e.getMessage());
            }
        }
        // 设为雪花ID
        user.setUserId(IdUtil.getSnowflakeNextId());
    }

    public void buildNickNameAndUserId1(SysUser user) {
        if (CharSequenceUtil.isNotBlank(user.getEmail())) {
            try {
                user.setNickName(NickNameGen.generateNicknameFromEmailPrefix(user.getEmail()));
            } catch (Exception e) {
                log.error("NickNameGen.generateNicknameFromEmailPrefix error: " + e.getMessage());
            }
        }
        // 设为雪花ID
        user.setUserId(IdUtil.getSnowflakeNextId());
    }

}
